[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { Comments } from '~/components/Comments';
  20. import { MainPane } from '~/components/Layout/MainPane';
  21. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  22. // import { useTranslation } from '~/i18n';
  23. import { PageContentFooter } from '~/components/PageContentFooter';
  24. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  25. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  26. import type { CrowiRequest } from '~/interfaces/crowi-request';
  27. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  28. // import { useRendererSettings } from '~/stores/renderer';
  29. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  30. import type { EditorConfig } from '~/interfaces/editor-settings';
  31. import type { RendererConfig } from '~/interfaces/services/renderer';
  32. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  33. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  34. import type { PageModel, PageDocument } from '~/server/models/page';
  35. import type { PageRedirectModel } from '~/server/models/page-redirect';
  36. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  37. import { useEditingMarkdown } from '~/stores/editor';
  38. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  39. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  40. import { useRedirectFrom } from '~/stores/page-redirect';
  41. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  42. import {
  43. useSelectedGrant,
  44. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  45. } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  49. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  50. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  51. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  52. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  53. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  54. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  55. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  56. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  57. import type { PageSideContentsProps } from '../components/PageSideContents';
  58. import {
  59. useCurrentUser,
  60. useIsLatestRevision,
  61. useIsForbidden, useIsNotFound, useIsSharedUser,
  62. useIsEnabledStaleNotification, useIsIdenticalPath,
  63. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  64. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  65. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  66. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  67. useIsSlackConfigured, useRendererConfig,
  68. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  69. } from '../stores/context';
  70. import { NextPageWithLayout } from './_app.page';
  71. import {
  72. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage,
  73. } from './utils/commons';
  74. declare global {
  75. // eslint-disable-next-line vars-on-top, no-var
  76. var globalEmitter: EventEmitter;
  77. }
  78. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  79. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  80. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  81. const PageSideContents = dynamic<PageSideContentsProps>(() => import('../components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  82. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  83. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  84. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  85. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  86. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  87. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  88. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  89. const logger = loggerFactory('growi:pages:all');
  90. const {
  91. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isCreatablePage, isTopPage,
  92. } = pagePathUtils;
  93. const { removeHeadingSlash } = pathUtils;
  94. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  95. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  96. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  97. {
  98. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  99. return v?.data != null
  100. && v?.data.toObject != null
  101. && v?.meta != null
  102. && isIPageInfoForEntity(v.meta);
  103. },
  104. serialize: (v) => {
  105. return {
  106. data: superjson.stringify(v.data.toObject()),
  107. meta: superjson.stringify(v.meta),
  108. };
  109. },
  110. deserialize: (v) => {
  111. return {
  112. data: superjson.parse(v.data),
  113. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  114. };
  115. },
  116. },
  117. 'IPageToShowRevisionWithMetaTransformer',
  118. );
  119. // GrowiContextualSubNavigation for NOT shared page
  120. type GrowiContextualSubNavigationProps = {
  121. isLinkSharingDisabled: boolean,
  122. }
  123. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  124. const { isLinkSharingDisabled } = props;
  125. const { data: currentPage } = useSWRxCurrentPage();
  126. return (
  127. <div data-testid="grw-contextual-sub-nav">
  128. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  129. </div>
  130. );
  131. };
  132. const IdenticalPathPage = (): JSX.Element => {
  133. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  134. return <IdenticalPathPage />;
  135. };
  136. const PutbackPageModal = (): JSX.Element => {
  137. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  138. return <PutbackPageModal />;
  139. };
  140. type Props = CommonProps & {
  141. currentUser: IUser,
  142. pageWithMeta: IPageToShowRevisionWithMeta | null,
  143. // pageUser?: any,
  144. redirectFrom?: string;
  145. // shareLinkId?: string;
  146. isLatestRevision?: boolean,
  147. isIdenticalPathPage?: boolean,
  148. isForbidden: boolean,
  149. isNotFound: boolean,
  150. isNotCreatable: boolean,
  151. // isAbleToDeleteCompletely: boolean,
  152. templateTagData?: string[],
  153. templateBodyData?: string,
  154. isSearchServiceConfigured: boolean,
  155. isSearchServiceReachable: boolean,
  156. isSearchScopeChildrenAsDefault: boolean,
  157. isSlackConfigured: boolean,
  158. // isMailerSetup: boolean,
  159. isAclEnabled: boolean,
  160. // hasSlackConfig: boolean,
  161. drawioUri: string | null,
  162. hackmdUri: string,
  163. noCdn: string,
  164. // highlightJsStyle: string,
  165. isAllReplyShown: boolean,
  166. isContainerFluid: boolean,
  167. editorConfig: EditorConfig,
  168. isEnabledStaleNotification: boolean,
  169. isEnabledAttachTitleHeader: boolean,
  170. // isEnabledLinebreaks: boolean,
  171. // isEnabledLinebreaksInComments: boolean,
  172. adminPreferredIndentSize: number,
  173. isIndentSizeForced: boolean,
  174. disableLinkSharing: boolean,
  175. rendererConfig: RendererConfig,
  176. // UI
  177. userUISettings?: IUserUISettings
  178. // Sidebar
  179. sidebarConfig: ISidebarConfig,
  180. };
  181. const Page: NextPageWithLayout<Props> = (props: Props) => {
  182. // const { t } = useTranslation();
  183. const router = useRouter();
  184. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  185. // register global EventEmitter
  186. if (isClient() && window.globalEmitter == null) {
  187. window.globalEmitter = new EventEmitter();
  188. }
  189. // commons
  190. useEditorConfig(props.editorConfig);
  191. useCsrfToken(props.csrfToken);
  192. // UserUISettings
  193. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  194. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  195. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  196. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  197. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  198. // page
  199. useIsLatestRevision(props.isLatestRevision);
  200. useIsContainerFluid(props.isContainerFluid);
  201. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  202. useIsForbidden(props.isForbidden);
  203. useIsNotFound(props.isNotFound);
  204. useIsNotCreatable(props.isNotCreatable);
  205. useRedirectFrom(props.redirectFrom ?? null);
  206. useIsSharedUser(false); // this page cann't be routed for '/share'
  207. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  208. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  209. useIsSearchPage(false);
  210. useTemplateTagData(props.templateTagData);
  211. useTemplateBodyData(props.templateBodyData);
  212. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  213. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  214. useIsSearchServiceReachable(props.isSearchServiceReachable);
  215. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  216. useIsSlackConfigured(props.isSlackConfigured);
  217. // useIsMailerSetup(props.isMailerSetup);
  218. useIsAclEnabled(props.isAclEnabled);
  219. // useHasSlackConfig(props.hasSlackConfig);
  220. useDrawioUri(props.drawioUri);
  221. useHackmdUri(props.hackmdUri);
  222. // useNoCdn(props.noCdn);
  223. useDefaultIndentSize(props.adminPreferredIndentSize);
  224. useIsIndentSizeForced(props.isIndentSizeForced);
  225. useDisableLinkSharing(props.disableLinkSharing);
  226. useRendererConfig(props.rendererConfig);
  227. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  228. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  229. useIsAllReplyShown(props.isAllReplyShown);
  230. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  231. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  232. const { pageWithMeta, userUISettings } = props;
  233. const pageId = pageWithMeta?.data._id;
  234. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  235. useCurrentPageId(pageId ?? null);
  236. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  237. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  238. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  239. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  240. useCurrentPathname(props.currentPathname);
  241. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  242. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  243. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  244. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  245. useSetupGlobalSocket();
  246. useSetupGlobalSocketForPage(pageId);
  247. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  248. const shouldRenderPutbackPageModal = pageWithMeta != null
  249. ? _isTrashPage(pageWithMeta.data.path)
  250. : false;
  251. // sync grant data
  252. useEffect(() => {
  253. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  254. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  255. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  256. useEffect(() => {
  257. const decodedURI = decodeURI(window.location.pathname);
  258. if (isClient() && decodedURI !== props.currentPathname) {
  259. const { search, hash } = window.location;
  260. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  261. }
  262. }, [props.currentPathname, router]);
  263. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  264. const title = generateCustomTitleForPage(props, pagePath ?? '');
  265. const sideContents = !props.isNotFound && !props.isNotCreatable
  266. ? (
  267. <PageSideContents page={pageWithMeta?.data} />
  268. )
  269. : <></>;
  270. const footerContents = !props.isIdenticalPathPage && !props.isNotFound && pageWithMeta != null
  271. ? (
  272. <>
  273. { pagePath != null && !isTopPagePath && (
  274. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  275. ) }
  276. { isUsersHomePage(pageWithMeta.data.path) && (
  277. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  278. ) }
  279. <PageContentFooter page={pageWithMeta.data} />
  280. </>
  281. )
  282. : <></>;
  283. return (
  284. <>
  285. <Head>
  286. <title>{title}</title>
  287. </Head>
  288. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  289. <header className="py-0 position-relative">
  290. <div id="grw-subnav-container">
  291. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  292. </div>
  293. </header>
  294. <div className="d-edit-none">
  295. <GrowiSubNavigationSwitcher />
  296. </div>
  297. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  298. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  299. <MainPane
  300. sideContents={sideContents}
  301. footerContents={footerContents}
  302. >
  303. <PageAlerts />
  304. { props.isIdenticalPathPage && <IdenticalPathPage />}
  305. { !props.isIdenticalPathPage && (
  306. <>
  307. { props.isForbidden && <ForbiddenPage /> }
  308. { props.isNotCreatable && <NotCreatablePage />}
  309. { !props.isForbidden && !props.isNotCreatable && <DisplaySwitcher />}
  310. </>
  311. ) }
  312. <PageStatusAlert />
  313. </MainPane>
  314. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  315. </div>
  316. </>
  317. );
  318. };
  319. Page.getLayout = function getLayout(page) {
  320. return (
  321. <>
  322. <DrawioViewerScript />
  323. <BasicLayoutWithEditorMode>
  324. {page}
  325. </BasicLayoutWithEditorMode>
  326. <UnsavedAlertDialog />
  327. <DescendantsPageListModal />
  328. <DrawioModal />
  329. <HandsontableModal />
  330. </>
  331. );
  332. };
  333. function getPageIdFromPathname(currentPathname: string): string | null {
  334. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  335. }
  336. class MultiplePagesHitsError extends ExtensibleCustomError {
  337. pagePath: string;
  338. constructor(pagePath: string) {
  339. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  340. this.pagePath = pagePath;
  341. }
  342. }
  343. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  344. const { model: mongooseModel } = await import('mongoose');
  345. const req: CrowiRequest = context.req as CrowiRequest;
  346. const { crowi } = req;
  347. const { revisionId } = req.query;
  348. const Page = crowi.model('Page') as PageModel;
  349. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  350. const { pageService } = crowi;
  351. let currentPathname = props.currentPathname;
  352. const pageId = getPageIdFromPathname(currentPathname);
  353. const isPermalink = _isPermalink(currentPathname);
  354. const { user } = req;
  355. if (!isPermalink) {
  356. // check redirects
  357. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  358. if (chains != null) {
  359. // overwrite currentPathname
  360. currentPathname = chains.end.toPath;
  361. props.currentPathname = currentPathname;
  362. // set redirectFrom
  363. props.redirectFrom = chains.start.fromPath;
  364. }
  365. // check whether the specified page path hits to multiple pages
  366. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  367. if (count > 1) {
  368. throw new MultiplePagesHitsError(currentPathname);
  369. }
  370. }
  371. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  372. const page = pageWithMeta?.data as unknown as PageDocument;
  373. // add user to seen users
  374. if (page != null && user != null) {
  375. await page.seen(user);
  376. }
  377. // populate & check if the revision is latest
  378. if (page != null) {
  379. page.initLatestRevisionField(revisionId);
  380. await page.populateDataToShowRevision();
  381. props.isLatestRevision = page.isLatestRevision();
  382. }
  383. if (page == null && user != null) {
  384. const templateData = await Page.findTemplate(props.currentPathname);
  385. if (templateData != null) {
  386. props.templateTagData = templateData.templateTags as string[];
  387. props.templateBodyData = templateData.templateBody as string;
  388. }
  389. }
  390. props.pageWithMeta = pageWithMeta;
  391. }
  392. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  393. const { model: mongooseModel } = await import('mongoose');
  394. const req = context.req as CrowiRequest<IUserHasId & any>;
  395. const { user } = req;
  396. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  397. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  398. if (userUISettings != null) {
  399. props.userUISettings = userUISettings.toObject();
  400. }
  401. }
  402. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  403. const req: CrowiRequest = context.req as CrowiRequest;
  404. const { crowi } = req;
  405. const Page = crowi.model('Page') as PageModel;
  406. const { currentPathname } = props;
  407. const pageId = getPageIdFromPathname(currentPathname);
  408. const isPermalink = _isPermalink(currentPathname);
  409. const page = props.pageWithMeta?.data;
  410. if (props.isIdenticalPathPage) {
  411. props.isNotCreatable = true;
  412. }
  413. else if (page == null) {
  414. props.isNotFound = true;
  415. props.isNotCreatable = !isCreatablePage(currentPathname);
  416. // check the page is forbidden or just does not exist.
  417. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  418. props.isForbidden = count > 0;
  419. }
  420. else {
  421. props.isNotFound = page.isEmpty;
  422. props.isNotCreatable = false;
  423. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  424. if (isPermalink && page.isEmpty) {
  425. props.currentPathname = page.path;
  426. }
  427. // /path/to/page ==> /62a88db47fed8b2d94f30000
  428. if (!isPermalink && !page.isEmpty) {
  429. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  430. if (!isToppage) {
  431. props.currentPathname = `/${page._id}`;
  432. }
  433. }
  434. }
  435. }
  436. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  437. // const req: CrowiRequest = context.req as CrowiRequest;
  438. // const { crowi } = req;
  439. // const UserModel = crowi.model('User');
  440. // if (isUserPage(props.currentPagePath)) {
  441. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  442. // if (user != null) {
  443. // props.pageUser = JSON.stringify(user.toObject());
  444. // }
  445. // }
  446. // }
  447. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  448. const req: CrowiRequest = context.req as CrowiRequest;
  449. const { crowi } = req;
  450. const {
  451. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  452. } = crowi;
  453. props.isSearchServiceConfigured = searchService.isConfigured;
  454. props.isSearchServiceReachable = searchService.isReachable;
  455. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  456. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  457. // props.isMailerSetup = mailService.isMailerSetup;
  458. props.isAclEnabled = aclService.isAclEnabled();
  459. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  460. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  461. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  462. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  463. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  464. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  465. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  466. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  467. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  468. props.editorConfig = {
  469. upload: {
  470. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  471. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  472. },
  473. };
  474. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  475. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  476. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  477. props.rendererConfig = {
  478. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  479. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  480. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  481. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  482. plantumlUri: process.env.PLANTUML_URI ?? null,
  483. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  484. // XSS Options
  485. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  486. tagWhiteList: crowi.xssService.getTagWhiteList(),
  487. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  488. // XSS: rehype-sanitize options
  489. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  490. };
  491. props.sidebarConfig = {
  492. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  493. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  494. };
  495. }
  496. /**
  497. * for Server Side Translations
  498. * @param context
  499. * @param props
  500. * @param namespacesRequired
  501. */
  502. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  503. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  504. props._nextI18Next = nextI18NextConfig._nextI18Next;
  505. }
  506. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  507. const req = context.req as CrowiRequest<IUserHasId & any>;
  508. const { user } = req;
  509. const result = await getServerSideCommonProps(context);
  510. // check for presence
  511. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  512. if (!('props' in result)) {
  513. throw new Error('invalid getSSP result');
  514. }
  515. const props: Props = result.props as Props;
  516. if (props.redirectDestination != null) {
  517. return {
  518. redirect: {
  519. permanent: false,
  520. destination: props.redirectDestination,
  521. },
  522. };
  523. }
  524. if (user != null) {
  525. props.currentUser = user.toObject();
  526. }
  527. try {
  528. await injectPageData(context, props);
  529. }
  530. catch (err) {
  531. if (err instanceof MultiplePagesHitsError) {
  532. props.isIdenticalPathPage = true;
  533. }
  534. else {
  535. throw err;
  536. }
  537. }
  538. await injectUserUISettings(context, props);
  539. await injectRoutingInformation(context, props);
  540. injectServerConfigurations(context, props);
  541. await injectNextI18NextConfigurations(context, props, ['translation']);
  542. return {
  543. props,
  544. };
  545. };
  546. export default Page;